package com.sttk.fastMark.camera.utils;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhttpUtils {


    public String BaseUrl = "http://aliv18.data.moji.com/";
    public String appCode = "81f380c9269a46b3a56dfbb0f7e2b755";

    private OkHttpClient mClient;
    private static volatile OkhttpUtils mOkUtils;//防止多个线程同时访问
    public static final int TIMEOUT = 60;//连接为20s，读取为40s；
    public static final int TIMEOUT1 = 60;//连接为20s，读取为40s；
    private Handler handler = new Handler(Looper.getMainLooper());


    public OkhttpUtils() {

        mClient = new OkHttpClient().newBuilder()
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT1, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT1, TimeUnit.SECONDS)
                .build();
        ;
    }

    //使用单利模式，通过获取的方式拿到对象（还为了优化内存，单利模式只可创建一次）z
    public static OkhttpUtils getInstance() {
        if (mOkUtils == null) {
            synchronized (OkhttpUtils.class) {
                if (mOkUtils == null) {
                    mOkUtils = new OkhttpUtils();

                }
            }
        }
        return mOkUtils;
    }

    /**
     * 应用拦截器
     */
    Interceptor appInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl url = request.url();
            String s = url.url().toString();
            Response response = chain.proceed(request);
            return response;
        }

    };


    /**
     * okhttp    不需要登录的接口
     */
    public void postNoLoginRequest(String url, Map<String, String> body, final HttpCallBack callBack) {
        //  RequestBody fileBody  = RequestBody.create(MediaType.parse("application/from-data"),excelFile);
        if (body != null && body.size() > 0) {
            body.put("cottonMotorbikePicture", "es");
        }
        FormBody.Builder builder = new FormBody.Builder();
        if (body != null && body.size() > 0) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                if (!TextUtils.isEmpty(entry.getValue())) {
                    builder.add(entry.getKey(), entry.getValue());
                }
            }
        }
    /*    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (body!=null&&body.size()>0){
            for (Map.Entry<String, String> entry : body.entrySet()) {
                if (!TextUtils.isEmpty(entry.getValue())){
                    builder.addFormDataPart(entry.getKey(),entry.getValue());
                }else {
                    builder.addFormDataPart(entry.getKey(),"");
                }
            }
        }*/
        Request request = new Request.Builder()
                .url(BaseUrl + url)
                .post(builder.build())
                .addHeader("upperKilogramUndergroundIncidentThere", "googleplay")

                .addHeader("endlessPowder", "")
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(callBack, e.getMessage());//java.net.ConnectException: Failed to connect to /123.127.93.180:93

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onSuccess(callBack, string);
            }
        });

    }
    //
    /**
     * okhttp    post请求  需要登录的接口
     */
    public void postRequest(String url, Map<String, String> body, final HttpCallBack callBack) {
        FormBody.Builder builder = new FormBody.Builder();
        if (body != null && body.size() > 0) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                if (!TextUtils.isEmpty(entry.getValue())) {
                    builder.add(entry.getKey(), entry.getValue());
                }
            }
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(BaseUrl + url)
                .post(requestBody)
                .addHeader("Authorization", "APPCODE " +appCode)
                .addHeader("appcode", appCode)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(callBack, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onSuccess(callBack, string);
            }
        });

    }

    public void postRaw(String url, String postBody, final HttpCallBack callBack) {
        MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(BaseUrl + url)
                .addHeader("upperKilogramUndergroundIncidentThere", "googleplay")

                .addHeader("unsafeToday", "1")//////固定传1
                .addHeader("endlessPowder", "")
                .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))

                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(callBack, e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onSuccess(callBack, string);
            }
        });
    }

    /**
     * okhttp    post请求  需要登录的接口
     */
    public void postImgRequest(String url, Map<String, String> body, String type, File file1, File file2, File file3, final HttpCallBack callBack) {
        if (body != null && body.size() > 0) {
            body.put("cottonMotorbikePicture", "es");
        }
        MultipartBody.Builder builder = null;
        if (type.equals("00")) {
            RequestBody fileBody1 = RequestBody.create(MediaType.parse("image/png"), file1);
            RequestBody fileBody2 = RequestBody.create(MediaType.parse("image/png"), file2);
            builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("contraryHappyGovernment", "frontImage", fileBody1)
                    .addFormDataPart("communistProBasicMicrowave", "backImage", fileBody2);
        } else if (type.equals("01")) {
            RequestBody fileBody1 = RequestBody.create(MediaType.parse("image/png"), file3);
            builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("contraryHappyGovernment", "frontImage", fileBody1);
        } else if (type.equals("02")) {
            builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        }

        if (body != null && body.size() > 0) {
            for (Map.Entry<String, String> entry : body.entrySet()) {
                if (!TextUtils.isEmpty(entry.getValue())) {
                    builder.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
        }
        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(BaseUrl + url)
                .post(requestBody)
                .addHeader("upperKilogramUndergroundIncidentThere", "googleplay")

                .addHeader("unsafeToday", "1")//////固定传1
                .addHeader("endlessPowder", "")
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(callBack, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onSuccess(callBack, string);
            }
        });

    }

    public void postZip(String url, String md5, String orderNo, String fileName, final HttpCallBack callBack) {
     /*   jsonObject.put("md5",md5);//String 文件MD5
        jsonObject.put("orderNo",orderNo);
        jsonObject.put("file",new File(path));//zip文件*/
        //RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        builder.addFormDataPart("md5", md5);//传递键值对参数
        builder.addFormDataPart("orderNo", orderNo);
        File file = new File(fileName);
        builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));//文件名,请求体里的文件
        Request request = null;
        // String appsFlyerUID = AppsFlyerLib.getInstance().getAppsFlyerUID(BaseApp.context);// 对接第三方appsflyer
        request = new Request.Builder()
                .url(BaseUrl + url)
                .post(builder.build())
                /*      .addHeader("Authorization", "Bearer" + getToken())
                      .addHeader("Content-Type", "multipart/form-data")
                      .addHeader("packageName", BaseApp.context.getPackageName())
                      .addHeader("@string/app_name", PhoneUtils.getAppName(BaseApp.context))
                      .addHeader("lang", "es")
                      .addHeader("afid",appsFlyerUID)*/
                .build();


        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(callBack, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onSuccess(callBack, string);
            }
        });

    }

    /**
     * okhttp    post请求
     */
    public void postLoginJson(String url, String phone, String code, final HttpCallBack callBack) {
        // String args = SPUtil.getString(BaseApp.context, "args", "");
        String macAddress = "";

        FormBody formBody = new FormBody.Builder()
/*        .add("mobile", phone)
        .add("verifyCode", code)//验证码
        .add("adrVersion", Build.VERSION.SDK_INT+"")//android版本号Build.VERSION.SDK_INT
        .add("appVersion", BuildConfig.VERSION_NAME)
        .add("channelId", PhoneUtils.getAppName(BaseApp.context))//String 渠道id (如SmartLoan)
        .add("imei",PhoneUtils.getIMEI(BaseApp.context))
        .add("packageName", BaseApp.context.getPackageName())
        .add("mac",macAddress)
        .add("androidId", Settings.System.getString(BaseApp.context.getContentResolver(), Settings.System.ANDROID_ID))
        .add("releaseDate", Build.TIME+"")
        .add("isRooted", PhoneUtils.isDeviceRooted()+"")
        .add("timeZone", TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT))
        .add("timeZoneId", TimeZone.getDefault().getID())
        .add("installReferce", args)
        .add("@string/app_name", PhoneUtils.getAppName(BaseApp.context))
        .add("verified", false+"")//Boolean 是否手动输入验证码，是：true，自动登录为否：false*/
                .build();
        Request request = null;
        //   String appsFlyerUID = AppsFlyerLib.getInstance().getAppsFlyerUID(BaseApp.context);//对接第三方appsflyer
        request = new Request.Builder()
                .url(BaseUrl + url)
                .post(formBody)
                /*          .addHeader("Authorization", "Bearer" + getToken())
                          .addHeader("Content-Type", "application/x-www-form-urlencoded")
                          .addHeader("packageName", BaseApp.context.getPackageName())
                          .addHeader("@string/app_name", PhoneUtils.getAppName(BaseApp.context))
                          .addHeader("lang", "es")
                           .addHeader("afid",appsFlyerUID)*/
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(callBack, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                onSuccess(callBack, string);
            }
        });

    }

    public void onSuccess(final HttpCallBack callBack, final String data) {
        if (callBack != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {//在主线程操作
                    if (!TextUtils.isEmpty(data)) {
                        callBack.onSusscess(data);
                    }
                }
            });
        }
    }


    public void onFail(final HttpCallBack callBack, final String msg) {
        if (callBack != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    callBack.onFail(msg);

                }
            });
        }
    }


    public static abstract class HttpCallBack {
        //成功回调
        public abstract void onSusscess(String data);

        //失败
        public abstract void onFail(String meg);

    }




}

